﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using MovieCriticsPage;

namespace MovieCriticsPage.Account
{
    public partial class Login : System.Web.UI.Page
    {
        public new TheApplication Application
        {
            get { return TheApplication.Current; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        }

        protected void LoginButton_OnClick(object sender, EventArgs e)
        {
            var username = this.LoginUser.UserName;

            if (this.Application.Database.users.Any(user => user.u_userName == username))
            {
                // TODO: check password 



                var current_user = this.Application.Database.users.Where(user => user.u_userName == username).Select(user => 
                        new MovieCriticsUser {
                            UserName = user.u_userName,
                            UserID = user.u_userID,
                            emailAddress = user.u_emailAddress
                        } ).FirstOrDefault();

                TheApplication.Current.ApplicationUser = current_user;
                FormsAuthentication.SetAuthCookie(username, false);
                FormsAuthentication.RedirectFromLoginPage(username, false);
            }
        }

    }
}
